package org.jenijo.querydroid;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class ResultsActivity extends Activity implements OnClickListener {
	private int							qcm_id;
	private HashMap<Integer, Integer>	answersMap;
	private TextView					score;
	private ProgressBar					prog;
	private LinearLayout				answerContainer;
	private String						server, login, password;
	private Handler						handler;
	private Button						exitBut;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		setContentView(R.layout.result);
		
		ServerErrorHandler.ctx = this;
		
		Intent i = getIntent();
		qcm_id = i.getIntExtra("qcm_id", -1);
		answersMap = (HashMap<Integer, Integer>) i.getSerializableExtra("answers");
		server = i.getStringExtra("server");
		login = i.getStringExtra("login");
		password = i.getStringExtra("password");
		
		handler = new Handler();
		
		score = (TextView) findViewById(R.id.tvScore);
		prog = (ProgressBar) findViewById(R.id.progBarRes);
		answerContainer = (LinearLayout) findViewById(R.id.llAnswers);
		exitBut = (Button) findViewById(R.id.exitBut);
		
		exitBut.setOnClickListener(this);
		
		Set<Entry<Integer, Integer>> set = answersMap.entrySet();
		Iterator<Entry<Integer, Integer>> iter = set.iterator();
		
		while(iter.hasNext()){
			TableLayout table = (TableLayout) LayoutInflater.from(this).inflate(R.layout.table, null);
			
			{
				TableRow row = (TableRow) LayoutInflater.from(this).inflate(R.layout.tablerow, null);
				
				TextView q = (TextView) row.findViewById(R.id.question);
				q.setText(R.string.questionTextView);
				
				TextView a = (TextView) row.findViewById(R.id.answer);
				a.setText(R.string.answerTextView);
				
				table.addView(row);
			}
			
			int j = 0;
			while(iter.hasNext() && j < 15){
				Entry<Integer, Integer> e = iter.next();
				TableRow row = (TableRow) LayoutInflater.from(this).inflate(R.layout.tablerow, null);
				row.setId(e.getKey());
				
				TextView q = (TextView) row.findViewById(R.id.question);
				q.setText(Integer.toString(e.getKey()));
				
				TextView a = (TextView) row.findViewById(R.id.answer);
				a.setText(Integer.toString(e.getValue()));
				
				table.addView(row);
				j++;
			}
			answerContainer.addView(table);
		}
		
		new AsyncTask<Void, Integer, Integer>() {
			protected void onPreExecute() {
				prog.setMax(answersMap.size());
			}
			
			@Override
			protected Integer doInBackground(Void... arg0) {
				String url = "http://" + server + "/android/qcm/submit";
				
				int score = 0;
				
				String jsonResult = null;
				
				JSONObject jso, res;
				
				Set<Entry<Integer, Integer>> set = answersMap.entrySet();
				Iterator<Entry<Integer, Integer>> iter = set.iterator();
				
				while(iter.hasNext()){
					Entry<Integer, Integer> e = iter.next();
					RestClient client = new RestClient(url);
					client.addParam("login", login).addParam("password", password);
					
					jso = new JSONObject();
					
					try{
						jso.put("type", "qcmResult");
						res = new JSONObject();
						res.put("qcm_id", qcm_id);
						res.put("num_quest", e.getKey());
						res.put("num_rep", e.getValue());
						jso.put("content", res);
						
						client.addParam("json", jso.toString());
						
						client.execute(RequestMethod.POST);
						
						if(client.getResponse() != null){
							jsonResult = client.getResponse();
							
							JSONObject parsedJsonResult = new JSONObject(jsonResult);
							String type = parsedJsonResult.getString("type");
							if(type.equals("submitSuccess")){
								int answerScore = parsedJsonResult.getInt("result");
								publishProgress(e.getKey(), answerScore);
								score += answerScore;
							}else{
								handler.post(new MessageHandler(getString(R.string.questionTextView)
										+ " "
										+ e.getKey()
										+ " : "
										+ ServerErrorHandler.err(parsedJsonResult.getString("message"))));
							}
						}else{
							handler.post(new MessageHandler(client.getErrorMessage()));
						}
					}catch (JSONException e1){
						handler.post(new MessageHandler(e1.getLocalizedMessage() + "\n"
								+ jsonResult));
					}catch (UnsupportedEncodingException e2){
						
					}
				}
				return score;
			}
			
			@Override
			protected void onPostExecute(Integer result) {
				super.onPostExecute(result);
				score.setText(String.valueOf((int) (((float) result.floatValue() * 100) / ((float) answersMap.size())))
						+ " %");
			}
			
			@Override
			protected void onProgressUpdate(Integer... values) {
				super.onProgressUpdate(values);
				prog.incrementProgressBy(1);
				TableRow row = (TableRow) answerContainer.findViewById(values[0]);
				TextView a = (TextView) row.findViewById(R.id.answer);
				if(values[1] == 1){
					a.setBackgroundColor(Color.GREEN);
				}else{
					a.setBackgroundColor(Color.RED);
				}
			}
		}.execute();
	}
	
	private class MessageHandler implements Runnable {
		String	mess;
		
		public MessageHandler(String msg) {
			mess = msg;
		}
		
		public void run() {
			new AlertDialog.Builder(ResultsActivity.this).setTitle(R.string.error).setMessage(mess).setPositiveButton(R.string.okButton, null).show();
		}
	}
	
	public void onClick(View arg0) {
		Intent i = new Intent();
		i.putExtra("qcm_id", qcm_id);
		setResult(RESULT_OK, i);
		finish();
	}
}
